package org.jbp.timelapse;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.AsyncTask;

public class SavePictureTask extends AsyncTask<TimeLapsePictureData, Void, Void>
{
	public static String getPictureName(int sequenceNumber)
	{
		if(sequenceNumber < 10)
			return "0000"+sequenceNumber+TimeLapseConstants.DEFAULT_EXTENSION;
		if(sequenceNumber < 100)
			return "000"+sequenceNumber+TimeLapseConstants.DEFAULT_EXTENSION;
		if(sequenceNumber < 1000)
			return "00"+sequenceNumber+TimeLapseConstants.DEFAULT_EXTENSION;
		if(sequenceNumber < 10000)
			return "0"+sequenceNumber+TimeLapseConstants.DEFAULT_EXTENSION;
		return sequenceNumber+TimeLapseConstants.DEFAULT_EXTENSION;
	}
	
	@Override
	protected Void doInBackground(TimeLapsePictureData... params)
	{
		if(params != null && params.length > 0)
		{
			TimeLapsePictureData pictureData = params[0];
			byte[] data = pictureData.getData();
			String fileName = pictureData.getName();
			FileOutputStream fos = null;
			try
			{
				fos = new FileOutputStream(TimeLapseConstants.DEFAULT_DIR+fileName);
				fos.write(data);
				fos.close();
				if(PictureLogger.getInstance() != null)
					PictureLogger.getInstance().logPicture(pictureData);
			}
			catch(FileNotFoundException e)
			{
				e.printStackTrace();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
		}
		return null;
	}
}